package com.xjzd.std.concurrency;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class CreateThread {

    public static void main1(String[] args) {
        MyJob t1 = new MyJob();
        t1.start();

        for (int i = 0; i < 100; i++) {
            System.out.println("Main Thread: " + i);
        }
    }

    public static void main2(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread t1 = new Thread(myRunnable);
        t1.start();

        for (int i = 0; i < 100; i++) {
            System.out.println("Main Thread: " + i);
        }
    }

    public static void main3(String[] args) {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                System.out.println("MyRunnable: " + i);
            }
        });
        t1.start();

        for (int i = 0; i < 100; i++) {
            System.out.println("Main Thread: " + i);
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // MyCallable myCallable = new MyCallable();
        // FutureTask<Integer> futureTask = new FutureTask<>(myCallable);
        FutureTask<Integer> futureTask = new FutureTask<>(() -> {
            int count = 0;
            for (int i = 0; i < 100; i++) {
                count += i;
            }
            return count;
        });
        Thread t1 = new Thread(futureTask);
        t1.start();

        for (int i = 0; i < 100; i++) {
            System.out.println("Main Thread: " + i);
        }

        System.out.println(futureTask.get());
    }
}

// 方式一
class MyJob extends Thread {

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("MyJob: " + i);
        }
    }
}

// 方式二
class MyRunnable implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("MyRunnable: " + i);
        }
    }
}

// 方式三
class MyCallable implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        int count = 0;
        for (int i = 0; i < 100; i++) {
            count += i;
        }
        return count;
    }
}
